package leetcode

//https://leetcode.com/problems/validate-ip-address/

fun main(args: Array<String>) {

}

fun validIPAddress(IP: String): String {

    if (isIpV4(IP))
        return "IPV4"
    if (isIpV6(IP))
        return "IPV6"
    return "Neither"

}

fun isIpV4(ip: String): Boolean {
    val parts = ip.split(".")
    if (parts.size == 4) {
        parts.forEach {
            if (it.length > 1 && it.first() == '0') return false
            else {
                it.forEach {
                    if (it !in '0'..'9')
                        return false
                }

                if (it.toInt() !in 0..255)
                    return false

            }
        }
        return true
    }
    return false
}

fun isIpV6(ip: String): Boolean {
    val parts = ip.split(":")
    if (parts.size == 8) {
        parts.forEachIndexed { index, it ->
            it.forEach {
                if (it !in '0'..'9' && it !in 'A'..'F' && it !in 'a'..'f')
                    return false

            }

            if (index == 0) {

                try {
                    if (it.toInt() == 0 && it.length > 1)
                        return false
                } catch (e: NumberFormatException) {

                }

            }

        }
        return true
    }

    return false
}